import 'package:bilibili/http/dao/home_dao.dart';
import 'package:bilibili/navigator/hi_navigator.dart';
import 'package:bilibili/page/home_tab_page.dart';
import 'package:bilibili/util/toast.dart';
import 'package:bilibili/widget/hi_tab_bar.dart';
import 'package:bilibili/widget/navigation_bar.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart' hide Banner;
import 'package:hi_net/http/core/hi_error.dart';
import 'package:lottie/lottie.dart';

import '../gen/assets.gen.dart';
import '../http/model/banner_mo.dart';
import '../http/model/home_mo.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  RouteChangeListener? _changeListener;
  late TabController _tabController;
  final List<String> _tabs = List.empty(growable: true);
  late List<BannerMo> _bannerList;

  @override
  void initState() {
    super.initState();
    HiNavigator hiNavigator = HiNavigator.getInstance();
    _changeListener = (RouteStatusInfo current, RouteStatusInfo? pre) {
      if (current.page is HomePage && pre?.page is! HomePage) {
        if (kDebugMode) {
          print("Home page resume");
        }
      }

      if (current.page is! HomePage && pre?.page is HomePage) {
        if (kDebugMode) {
          print("Home page pause");
        }
      }
    };
    hiNavigator.addChangeListener(_changeListener!);
  }

  _appbar() {
    return Padding(
      padding: const EdgeInsets.only(left: 10, right: 10),
      child: Row(children: [
        ClipOval(
          child: Assets.images.avatar.image(width: 40, height: 40),
        ),
        Expanded(
            child: Padding(
          padding: const EdgeInsets.only(left: 15, right: 15),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(16),
            child: Container(
              padding: const EdgeInsets.only(left: 10),
              height: 32,
              alignment: Alignment.centerLeft,
              decoration: BoxDecoration(color: Colors.grey[100]),
              child: const Icon(
                Icons.search,
                color: Colors.grey,
              ),
            ),
          ),
        )),
        const Icon(
          Icons.explore_outlined,
          color: Colors.grey,
        ),
        const Padding(
          padding: EdgeInsets.only(left: 12),
          child: Icon(
            Icons.mail_outline,
            color: Colors.grey,
          ),
        )
      ]),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
    HiNavigator hiNavigator = HiNavigator.getInstance();
    if (_changeListener != null) {
      hiNavigator.removeChangeListener(_changeListener!);
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<String>>(
        future: _loadData(),
        builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.data != null) {
              _tabs.clear();
              _tabs.addAll(snapshot.data!);
              _tabController = TabController(length: _tabs.length, vsync: this);
            }
            return _homeScaffold();
          } else {
            return Lottie.asset("assets/loading.json");
          }
        });
  }

  Future<List<String>> _loadData() async {
    try {
      HomeMo homeMo = await HomeDao.get("推荐");
      var categoryList = homeMo.categoryList ?? [];
      var list = categoryList.map((category) {
        return category.name;
      }).toList();
      _bannerList = homeMo.bannerList ?? [];
      return list;
    } on NeedLogin catch (e) {
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      showWarnToast(e.message);
    }

    return List.empty();
  }

  Widget _homeScaffold() {
    return Scaffold(
        body: Column(
      children: [
        context.commonStatusBar(child: _appbar()),
        Container(
          child: _tabBar(),
        ),
        Flexible(
            child: TabBarView(
                controller: _tabController,
                children: _tabs.map((label) {
                  return HomeTabPage(
                    label: label,
                    bannerList: label == "推荐" ? _bannerList : null,
                  );
                }).toList()))
      ],
    ));
  }

  ///自定义顶部tab
  _tabBar() {
    return HiTabBar(
      tabs: _tabs.map((tab) {
        return Tab(text: tab);
      }).toList(),
      controller: _tabController,
      fontSize: 16,
    );
  }
}
